import React from 'react'
import {User} from '../Screens/ProjectList/searchPanel'

const apiUrl = process.env.REACT_APP_API_URL
const localStorageKey = '__auth_provider_token__'
//从本地存储localStorage中获取token
export const getToken = ()=>window.localStorage.getItem(localStorageKey)

//把 user 的 token 信息存储到 localStorage 中
export const handleUserResponse = ({user}:{user:User})=>{
    window.localStorage.setItem(localStorageKey,user.token||'')
    return user
}

//登录
export const login = async (data:{username:string;password:string})=>{
    const response = await fetch(`${apiUrl}/login`, {
        method: 'POST',
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    })
    if (response.ok) {
        return handleUserResponse(await response.json())
    } else {
        return Promise.reject(data)
    }
}

//注册
export const register = (data:{username:string;password:string})=>{
    return fetch(`${apiUrl}/register`,{
        method: 'POST',
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    }).then(async(response)=>{
        if(response.ok){
            return handleUserResponse(await response.json())
        }else{
            return Promise.reject(data)
        }
    })
}

//登出
export const logout = async ()=>window.localStorage.response(localStorageKey)
